package com.jkj.utils;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class TTSUtils {
    private boolean isStarted = false;
    private Object lockObj = new Object();

    public static void main(String[] args) throws Exception {
        TTSUtils tts = new TTSUtils();
        boolean flag = tts.trans("AGV急停被按下");
        System.out.println(flag);
        Thread.sleep(5000);
        flag = tts.trans("AGV脱轨");
        System.out.println(flag);
    }

    public boolean trans(String text) {
        synchronized (lockObj) {
            if (isStarted) {
                return false;
            }
            isStarted = true;
            new Thread(() -> {
                ActiveXComponent activeXComponent = null;
                try {
                    //jacob封装好的可供选择的API
                    activeXComponent = new ActiveXComponent("Sapi.SpVoice");
                    //运行时输出语音内容
                    Dispatch dispatch = activeXComponent.getObject();
                    //设置音量
                    activeXComponent.setProperty("Volume", new Variant(100));
                    //语音的朗读速度-10到 +10
                    activeXComponent.setProperty("Rate", new Variant(-1));
                    //调用执行朗读
                    Dispatch.call(dispatch, "Speak", new Variant(text));
                    dispatch.safeRelease();
                    activeXComponent.safeRelease();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                isStarted = false;
            }).start();
            return true;
        }
    }
}
